import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
import vuexPersist from "vuex-persist";
import { Dialog } from 'vant';
export default new Vuex.Store({
  state: {
    shoplist: [],
  },
  mutations: {
    // 添加购物车
    add(state, item) {
      var flag = false;
      // 如果有此商品让它的数量添加
      state.shoplist.forEach((i) => {
        if (i.id == item.id) {
          flag = true;
          i.num++;
        }
      })
      // 如果没有此商品向购物车添加一条数据
      if (flag == false) {
        item.num = 1;
        state.shoplist.push(item);
      }
    },
    // 加
    jia(state, id) {
      state.shoplist.forEach((item) => {
        if (item.id == id) {
          item.num++;
        }
      })
    },
    // 减
    jian(state, id) {
      state.shoplist.forEach((item) => {
        if (item.id == id) {
          item.num--;
        }
      })
    },
    //  删除
    del(state, id) {
      Dialog.confirm({
        message: '确定要删除吗？',
      })
        .then(() => {
          state.shoplist.forEach((item, index) => {
            if (item.id == id) {
              state.shoplist.splice(index, 1);
            }
          })
        })
        .catch(() => {
        });
    }
  },
  actions: {
  },
  modules: {
  },
  plugins: [
    new vuexPersist({
      storage: window.localStorage,
    }).plugin,
  ],
})